// 饮水时间表
const WATER_SCHEDULE = {
    '07:00': '早晨起床后的第一杯水，帮助肾脏和肝脏解毒',
    '09:00': '工作开始，喝一杯温开水提供能量',
    '11:00': '工作进行中，补充水分放松心情',
    '13:00': '午睡醒来，喝水清醒提神',
    '15:00': '下午茶时间，提神醒脑',
    '18:00': '下班前，缓解疲劳',
    '19:30': '晚餐后，促进消化吸收',
    '21:30': '睡前最后一杯水，注意适量'
};

// 音效资源
const SOUND_EFFECTS = [
    'assets/1.mp3',
    'assets/2.mp3'
];

class WaterReminder {
    constructor() {
        this.currentAudio = null;
        this.detailsDialog = null;
        this.initializeUI();
        this.setupEventListeners();
        this.checkTime();
        this.updateCurrentTime();
    }

    updateCurrentTime() {
        const currentMessage = document.getElementById('currentMessage');
        const updateTime = () => {
            const now = new Date();
            const year = now.getFullYear();
            const month = String(now.getMonth() + 1).padStart(2, '0');
            const day = String(now.getDate()).padStart(2, '0');
            const hours = String(now.getHours()).padStart(2, '0');
            const minutes = String(now.getMinutes()).padStart(2, '0');
            const seconds = String(now.getSeconds()).padStart(2, '0');
            currentMessage.textContent = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        };
        updateTime();
        setInterval(updateTime, 1000);
    }

    initializeUI() {
        // 初始化详情对话框
        this.createDetailsDialog();
    }

    createDetailsDialog() {
        const dialog = document.createElement('dialog');
        dialog.className = 'details-dialog';
        dialog.innerHTML = `
            <div class="dialog-content">
                <div class="dialog-header">
                    <h2>饮水时间表</h2>
                    <button class="close-button">×</button>
                </div>
                <div class="schedule-container">
                    ${Object.entries(WATER_SCHEDULE).map(([time, desc]) => `
                        <div class="schedule-item">
                            <div class="time">${time}</div>
                            <div class="description">${desc}</div>
                        </div>
                    `).join('')}
                </div>
                <div class="analysis-container">
                    <h3>身体数据分析</h3>
                    <form id="analysisForm">
                        <div class="form-group">
                            <label>身高 (cm):</label>
                            <input type="number" name="height" required>
                        </div>
                        <div class="form-group">
                            <label>体重 (kg):</label>
                            <input type="number" name="weight" required>
                        </div>
                        <div class="form-group">
                            <label>性别:</label>
                            <select name="gender" required>
                                <option value="male">男</option>
                                <option value="female">女</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>运动频率:</label>
                            <select name="activity" required>
                                <option value="low">低频率</option>
                                <option value="medium">中频率</option>
                                <option value="high">高频率</option>
                            </select>
                        </div>
                        <button type="submit" class="analyze-button">分析</button>
                    </form>
                    <div id="analysisResult" class="analysis-result"></div>
                </div>
            </div>
        `;
        document.body.appendChild(dialog);
        this.detailsDialog = dialog;

        // 绑定关闭按钮事件
        dialog.querySelector('.close-button').addEventListener('click', () => {
            dialog.close();
        });

        // 绑定表单提交事件
        dialog.querySelector('#analysisForm').addEventListener('submit', (e) => {
            e.preventDefault();
            this.handleAnalysisSubmit(e.target);
        });
    }

    setupEventListeners() {
        // 绑定音效按钮事件
        document.getElementById('soundButton').addEventListener('click', () => {
            this.playRandomSound();
        });

        // 绑定详情按钮事件
        document.getElementById('detailsButton').addEventListener('click', () => {
            this.detailsDialog.showModal();
        });
    }

    async handleAnalysisSubmit(form) {
        const formData = new FormData(form);
        const data = Object.fromEntries(formData.entries());
        
        // 构建用户数据字符串
        const userInfo = `身高: ${data.height}cm\n体重: ${data.weight}kg\n性别: ${data.gender === 'male' ? '男' : '女'}\n运动频率: ${data.activity}`;
        
        const content_text = `
1、Agent 角色定义
定位为专业身材管理师，需基于用户提供的身体数据（身高、体重、体脂率等）和生活习惯（运动频率、饮食偏好等）生成个性化管理方案。
返回BMI值的时候，直接写公式与结果即可，不需要额外解释。
2、用户数据
${userInfo}

3、输出要求
请根据以上数据进行分析并给出：
- 身体状况评估
- 健康建议
- 运动计划
- 饮食建议
`;

        try {
            const response = await fetch("https://api.siliconflow.cn/v1/chat/completions", {
                method: "POST",
                headers: {
                    Authorization: "Bearer sk-sksltxovybtraaatdiifuwdpybfwlmplbqzvhasrmgtmegeb",
                    "Content-Type": "application/json"
                },
                body: JSON.stringify({
                    messages: [
                        {
                            content: content_text,
                            role: "user"
                        }
                    ],
                    model: "Qwen/Qwen2.5-7B-Instruct"
                })
            });

            if (!response.ok) {
                throw new Error(`请求失败: ${response.status}`);
            }

            const result = await response.json();
            
            if (!result || !result.choices || !result.choices[0]) {
                throw new Error('分析请求失败：返回数据格式错误');
            }
            this.displayAnalysisResult(result.choices[0]['message']['content']);
        } catch (error) {
            console.error('分析出错:', error);
            this.displayAnalysisResult({
                error: `分析服务出错：${error.message || '请稍后再试'}`
            });
        }
    }

    displayAnalysisResult(result) {
        const resultDiv = document.getElementById('analysisResult');
        if (!resultDiv) {
            console.error('分析结果容器不存在');
            return;
        }

        // 处理空值或错误情况
        if (!result) {
            resultDiv.innerHTML = '<p class="error-message">暂无分析结果</p>';
            return;
        }

        if (result.error) {
            resultDiv.innerHTML = `<p class="error-message">${result.error}</p>`;
            return;
        }

        // 解析API返回的字符串内容
        let analysisContent = '';
        if (typeof result === 'string') {
            // 将返回的字符串按照不同部分进行分割
            const sections = [
                { title: '身体状况评估', pattern: /###\s*身体状况评估[\s\S]*?(?=###|$)/i },
                { title: '健康建议', pattern: /###\s*健康建议[\s\S]*?(?=###|$)/i },
                { title: '运动计划', pattern: /###\s*运动计划[\s\S]*?(?=###|$)/i },
                { title: '饮食建议', pattern: /###\s*饮食建议[\s\S]*?(?=###|$)/i }
            ];

            // 提取每个部分的内容
            analysisContent = sections.map(section => {
                const match = result.match(section.pattern);
                const content = match ? match[0].replace(new RegExp(`###\\s*${section.title}`), '').trim() : '暂无数据';
                return `
                    <div class="analysis-section">
                        <h4>${section.title}</h4>
                        <div class="section-content">${content.replace(/\n/g, '<br>')}</div>
                    </div>
                `;
            }).join('');
        }

        // 更新结果显示
        resultDiv.innerHTML = analysisContent;
        resultDiv.style.display = 'block';
    }

    playRandomSound() {
        if (this.currentAudio) {
            this.currentAudio.pause();
            this.currentAudio = null;
            document.querySelector('.heart_left').style.background = 'linear-gradient(rgb(227, 7, 206),rgb(202, 125, 212) 50%,#fc8cfc)';
            document.querySelector('.heart_right').style.background = 'linear-gradient(rgb(227, 7, 206),rgb(202, 125, 212) 50%,#fc8cfc)';
        } else {
            const randomSound = SOUND_EFFECTS[Math.floor(Math.random() * SOUND_EFFECTS.length)];
            const audio = new Audio(randomSound);
            audio.play();
            this.currentAudio = audio;
            document.querySelector('.heart_left').style.background = 'linear-gradient(red, #fc8cfc 50%, hotpink, pink, #f9cff7)';
            document.querySelector('.heart_right').style.background = 'linear-gradient(red, hotpink 50%, #fc8cfc, pink, #f9cff7)';
        }
    }

    checkTime() {
        const now = new Date();
        const currentTime = now.toLocaleTimeString('zh-CN', {
            hour: '2-digit',
            minute: '2-digit',
            hour12: false
        });

        // 检查是否到达提醒时间
        if (WATER_SCHEDULE[currentTime]) {
            document.getElementById('currentMessage').textContent = WATER_SCHEDULE[currentTime];
            this.playRandomSound();
        }

        // 计算下次提醒时间
        const times = Object.keys(WATER_SCHEDULE).sort();
        const nextTime = times.find(time => time > currentTime) || times[0];
        document.getElementById('nextReminder').textContent = `下次提醒：${nextTime}`;

        // 每分钟检查一次
        setTimeout(() => this.checkTime(), 60000);
    }
}

// 初始化应用
document.addEventListener('DOMContentLoaded', () => {
    new WaterReminder();
});